from flask import Flask
from flask_restful import reqparse, Resource, Api, fields, marshal_with, marshal


app = Flask(__name__)
api = Api(app)

"""
Flask-RESTful 提供了marshal工具，用来帮助我们将数据序列化为特定格式的字典数据，以便作为视图的返回值
"""

resource_fields = {
    'name': fields.String,
    'age': fields.Integer,
    'address': fields.String,
}

class User(object):
    def __init__(self, name, age, address):
        self.name = name
        self.age = age
        self.address = address


class User1Resource(Resource):

    """
    {
    "data1": {
        "name": "lisi",
        "age": 11,
        "address": "\u90d1\u5dde\u5e02"
        }
    }
    """
    """装饰器方式"""
    @marshal_with(resource_fields, envelope='data1')
    def get(self):
        user = User('lisi', 11, '郑州市')
        return user

class User2Resource(Resource):

    """
    {
    "data2": [
        {
            "name": "lisi",
            "age": 11,
            "address": "\u90d1\u5dde\u5e02"
        },
        {
            "name": "zhangsan",
            "age": 12,
            "address": "\u90d1\u5dde\u5e02"
        }
        ]
    }
    """
    """不适用装饰器"""
    def get(self):
        user1 = User('lisi', 11, '郑州市')
        user2 = User('zhangsan', 12, '郑州市')
        lst = [user1, user2]
        return marshal(lst, resource_fields, envelope='data2')


api.add_resource(User1Resource, '/user1')
api.add_resource(User2Resource, '/user2')


if __name__ == '__main__':
    app.run(debug=True)


